<template>
  <div class="chat-main-wrap">
    <header>{{ gName }}</header>
    <main ref="main">
      <ul ref="ul">
        <li
          :class="item.uid === uid ? 'my' : 'other'"
          v-for="item in list"
          :key="item.id"
          :data-id="item.id"
        >
          <avatar
            :width="34"
            :height="34"
            :src="item.avatarUrl"
            class="avatar"
            v-if="!item.isWithDraw"
          />
          <div class="with-draw" v-if="item.isWithDraw">
            {{ (item.uid === uid ? "你" : item.nick) + "撤回了一条消息" }}
          </div>
          <div v-else-if="!item.isImg" class="msg-wrap">
            <div v-if="item.uid !== uid" class="name">{{ item.nick }}</div>
            <div class="msg">
              <div class="square"></div>
              <pre>{{ item.con }}</pre>
            </div>
          </div>
          <el-image
            v-else
            class="img-wrap"
            :src="item.imgUrl"
            fit="contain"
            :preview-src-list="[item.imgUrl]"
            @load="imgLoadOk"
          ></el-image>
          <div class="loading-wrap" v-if="item.uid === uid && !item.isConfirm">
            <i class="el-icon-loading"></i>
          </div>
        </li>
      </ul>
      <div ref="menu" class="right-menu"></div>
    </main>
    <footer>
      <div class="item-wrap">
        <i id="emoji-btn" class="el-icon-sunset" @click="showEmoji"></i>
        <div class="pic-sendfile-wrap">
          <i class="el-icon-picture-outline"></i>
          <input type="file" name="pic" @change="picChange" />
        </div>
        <i class="el-icon-scissors"></i>
        <i class="el-icon-chat-dot-round"></i>
      </div>
      <div class="text" ref="text" @input="textInput" contenteditable="true">
        {{ msgValue }}
      </div>
      <el-button size="mini" @click="sendGroupMsg_fn">发送(S)</el-button>
    </footer>
  </div>
</template>

<script>
import Avatar from "../../../components/coms/Avatar.vue";
import socket_m from "../../../util/connect";
import groupData_m from "../../../util/groupData";
import list_m from "../../../util/groupData";
import rightMenu_m from "../../../utils";

export default {
  data() {
    return {
      msgValue: "",
      uid: localStorage.getItem("uid"),
      name: localStorage.getItem("name"),
      avatarUrl: localStorage.getItem("avatarUrl"),
      nick: localStorage.getItem("nick"),
      list: list_m.getList(this.$store.state.chat.groupNum),
    };
  },
  methods: {
    picChange(e) {
      let file = e.target.files[0]; //得到该图片
      let reader = new FileReader(); //创建一个FileReader对象，进行下一步的操作
      reader.readAsDataURL(file); //通过readAsDataURL读取图片
      let self = this;
      reader.onload = function () {
        //读取完毕会自动触发，读取结果保存在result中
        let data = { img: this.result };
        groupData_m.addList({
          avatarUrl: self.avatarUrl,
          imgUrl: data.img,
          uid: self.uid,
          nick: self.nick,
          num: self.$store.state.chat.groupNum,
          isConfirm: false,
          isImg: true,
        });
        socket_m.sendMsg(
          "groupMsgImg",
          { base64Img: data.img, num: self.$store.state.chat.groupNum },
          (o) => {
            if (o.code === 0) {
              console.log(o);
              let item = groupData_m.groupList.find(
                (item1) => item1.num === o.num
              );
              if (item) {
                let item2 = item.messages.find((item3) => !item3.isConfirm);
                if (item2) {
                  item2.isConfirm = true;
                  item2.id = o.id;
                }
              }
            }
          },
          false
        );
      };
    },
    imgLoadOk() {
      this.$store.commit("g/setIsRecMsg_fn", true);
    },
    textInput(e) {
      // this.$store.commit("g/setMsgVal_fn", this.$refs.text.innerText);
      this.msgValue = this.$refs.text.innerText;
    },
    sendGroupMsg_fn() {
      this.$refs.text.focus();
      if (this.msgValue.trim() === "") {
        this.$message.warning("不能发送空白信息");
        return;
      }
      groupData_m.addList({
        avatarUrl: this.avatarUrl,
        // con: this.$refs.text.innerHTML + "",
        con: this.msgValue,
        uid: this.uid,
        nick: this.nick,
        num: this.$store.state.chat.groupNum,
        isConfirm: false,
      });
      socket_m.sendMsg(
        "groupMsg",
        {
          num: this.$store.state.chat.groupNum,
          con: this.msgValue,
          // con: this.$store.state.g.msgValue,
        },
        (o) => {
          if (o.code === 0) {
            let item = groupData_m.groupList.find(
              (item1) => item1.num === o.num
            );
            if (item) {
              let item2 = item.messages.find(
                (item3) => !item3.isConfirm && item3.con === o.con
              );
              if (item2) {
                item2.isConfirm = true;
                item2.id = o.id;
              }
            }
            this.msgValue = "";
            this.$store.commit("g/setIsRecMsg_fn", true);
          }
        },
        false
      );
      // this.$store.commit("g/clearMsgVal_fn");
      this.$refs.text.innerHTML = "";
    },
    // 发送图片
    sendImg() {},
    // 显示表情
    showEmoji() {
      // $(".text").emoji("show");
    },
  },
  watch: {
    "$store.state.chat.groupNum"(val) {
      this.list = list_m.getList(this.$store.state.chat.groupNum);
      setTimeout(() => {
        this.$store.commit("g/setIsRecMsg_fn", true);
      }, 0);
    },
    "$store.state.isLoadOk"(val) {
      this.list = list_m.getList(this.$store.state.chat.groupNum);
      // this.$refs.ul.scrollIntoView(false);
    },
    "$store.state.g.isRecMsg"(val) {
      if (val) {
        this.$refs.ul.scrollIntoView(false);
        this.$store.commit("g/setIsRecMsg_fn", false);
      }
    },
  },
  computed: {
    gName() {
      let tempGroups = this.$store.state.tempGroups;
      let g = tempGroups.find(
        (item) => item.num === this.$store.state.chat.groupNum
      );
      if (g) {
        return g.name;
      }
      return "";
    },
  },
  mounted() {
    let self = this;
    this.$refs.text.innerHTML = "";
    this.$refs.text.focus();
    this.$refs.text.onkeydown = function (e) {
      if (e.key === "Enter") {
        self.sendGroupMsg_fn();
        return false;
      }
    };

    // 初始化emoji
    $(".text").emoji({
      button: "#emoji-btn",
      icons: [
        {
          button: "#emoji-btn",
          name: "表情",
          path: "emoji/img/emoji/",
          maxNum: 91,
          excludeNums: [],
          file: ".png",
          placeholder: "#emoji_{alias}#",
        },
        {
          button: "#emoji-btn",
          name: "QQ表情",
          path: "emoji/img/qq/",
          maxNum: 91,
          excludeNums: [],
          file: ".gif",
          placeholder: "#qq_{alias}#",
        },
        {
          button: "#emoji-btn",
          name: "贴吧表情",
          path: "emoji/img/tieba/",
          maxNum: 91,
          excludeNums: [],
          file: ".jpg",
          placeholder: "#tieba_{alias}#",
        },
      ],
    });

    // 触发右键菜单
    this.$refs.ul.oncontextmenu = (e) => {
      this.$store.commit("updateRightMenuShow_fn", false);
      this.$store.state.rightMenuX = e.x;
      this.$store.state.rightMenuY = e.y;
      let liDom;
      if (
        e.target.className === "msg" ||
        e.target.parentNode.className === "msg" ||
        e.target.parentNode.classList.contains("img-wrap")
      ) {
        getLi(e.target);
        if (!liDom) {
          return;
        }
        let id = liDom.dataset.id;

        rightMenu_m.showList(2, id);
        this.$store.state.rightMenuX = e.x;
        this.$store.state.rightMenuY = e.y;
        this.$store.commit("updateRightMenuShow_fn", true);
      }
      return false;
      function getLi(el) {
        if (el) {
          if (el.className === "my") {
            liDom = el;
            return el;
          }
        } else {
          return null;
        }
        getLi(el.parentNode);
      }
    };
  },
  destroyed() {
    clearInterval(this.timer);
  },
  components: {
    Avatar,
  },
};
</script>
<style lang="less" scoped>
.chat-main-wrap {
  display: flex;
  height: 100%;
  flex-direction: column;
}
header {
  height: 60px;
  line-height: 60px;
  padding-left: 30px;
  border-bottom: 1px solid #ccc;
}
main {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  &::-webkit-scrollbar {
    width: 6px;
    height: 1px;
  }
  ul {
    padding-top: 30px;
    li {
      padding: 0 30px 15px;
      display: flex;
      .avatar {
        // width: 34px;
        // height: 34px;
      }
      .with-draw {
        width: 100%;
        text-align: center;
        color: #888;
        font-size: 13px;
      }
      .msg-wrap {
        display: flex;
        flex-direction: column;
        .name {
          color: #aaa;
          font-size: 12px;
          margin-bottom: 5px;
        }
        .msg {
          position: relative;
          margin: 0 10px;
          max-width: 282px;
          font-size: 14px;
          padding: 5px 10px;
          line-height: 21px;
          border-radius: 4px;
          pre {
            white-space: pre-wrap;
            word-wrap: break-word;
          }
          .square {
            width: 6px;
            height: 6px;
            background-color: #fff;
            position: absolute;
            top: 12px;
            transform: rotate(45deg);
          }
        }
      }
      .img-wrap {
        width: 175px;
        max-height: 175px;
        padding: 0 10px;
      }
      &.other {
        .name {
          padding-left: 10px;
        }
        .msg {
          background-color: #fff;
          border: 1px solid #ccc;
          &:hover {
            background-color: rgb(246, 246, 246);
            .square {
              background-color: rgb(246, 246, 246);
            }
          }
          .square {
            left: -4px;
            border-left: 1px solid #ccc;
            border-bottom: 1px solid #ccc;
          }
        }
      }
      &.my {
        justify-content: flex-start;
        flex-direction: row-reverse;
        .name {
          padding-right: 10px;
          text-align: right;
        }
        .msg {
          background-color: #9eea6a;
          border: 1px solid #9eea6a;
          &:hover {
            background-color: #98e165;
            .square {
              background-color: #98e165;
              border: 1px solid #98e165;
            }
          }
          .square {
            background-color: #9eea6a;
            border: 1px solid #9eea6a;
            right: -4px;
          }
        }
      }
      .loading-wrap {
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
  .right-menu {
    position: absolute;
  }
}
footer {
  width: 100%;
  height: 145px;
  border-top: 1px solid #ccc;
  position: relative;
  .item-wrap {
    display: flex;
    margin-top: 10px;
    & > i {
      margin-left: 30px;
      transform: scale(1.2);
    }
    .pic-sendfile-wrap {
      margin-top: -3px;
      margin-left: 30px;
      position: relative;
      & > i {
        transform: scale(1.2);
      }
      & > input {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
      }
    }
  }
  .text {
    width: 100%;
    box-sizing: border-box;
    padding: 0 30px;
    height: 80px;
    resize: none;
    margin: 0 auto;
    display: block;
    border: none;
    position: absolute;
    font-size: 14px;
    top: 30px;
    background-color: transparent;
    outline: none;
  }
  .el-button {
    position: absolute;
    right: 30px;
    bottom: 5px;
  }
}
</style>